<template>
    <div class="succession_container">
        <el-tabs v-model="activeName" class="demo-tabs" @tab-change="handleClick">
            <el-tab-pane label="在职继承" name="first">
                <div class="title-text">需要转接的客户</div>
                <el-select
                    v-model="formInline.trasferCustomer"
                    class="extend_select"
                    popper-class="zw-hide_select_option"
                    :popper-append-to-body="false"
                    :placeholder="selectText"
                    @mouseenter="selectFocus"
                    @mouseleave="selectBlur"
                    @click="handleTrasferCustomer">
                    <template #prefix>
                        <span style="padding: 2px 0 0 5px">
                            <el-icon style="width: 10px; height: 11px; color: #ff6b00"><user-filled /></el-icon>
                            <el-icon
                                v-if="isShowCler"
                                style="margin-left: 10px; width: 10px; height: 11px; color: #ff6b00"
                                @click.stop="clearData">
                                <circle-close-filled />
                            </el-icon>
                        </span>
                    </template>
                    <el-option></el-option>
                </el-select>
                <div class="title-text">将客户转接给</div>
                <el-select
                    v-model="dataParams.work_user_id"
                    :popper-append-to-body="false"
                    popper-class="zw-hide_select_option"
                    clearable
                    multiple
                    class="extend_select title-select"
                    placeholder="选接替的员工"
                    @click="handleTrasferTo"
                    @change="changeDepart">
                    <template #prefix>
                        <span style="padding: 2px 0 0 5px">
                            <el-icon style="width: 10px; height: 11px; color: #ff6b00"><user-filled /></el-icon>
                        </span>
                    </template>
                    <el-option v-for="item in creators" :key="item.id" :label="item.name" :value="item.id">
                        {{ item.name }}
                    </el-option>
                </el-select>
            </el-tab-pane>
            <el-tab-pane label="分配记录" name="second">
                <div class="succession_list">
                    <!--搜索栏-->
                    <ZwSearchForm row-num="3" :option="searchOption" @search="search" @reset="reset" />

                    <!--表格-->
                    <ZwTable
                        ref="tableRef"
                        class="table-box"
                        tab-h="calc(100vh - 300px)"
                        :option="tableOption"
                        :fetch-params="state.searchParams"
                        :fetch-api="fetchApi()">
                        <template #headerOperate>
                            <div class="export-btn">
                                <el-button v-auth="'ASSIGN_EXP'" type="primary" @click="exportData">
                                    导出列表
                                </el-button>
                            </div>
                        </template>
                    </ZwTable>
                </div>
            </el-tab-pane>
        </el-tabs>
        <div class="handle_button">
            <div v-if="isHand">
                <el-popover placement="top-start" :width="200" trigger="click">
                    <template>
                        <p>你有{{ handovering }}个移交任务正在进行中，请完成后再操作！</p>
                        <div class="d-flex jc-end">
                            <el-link type="primary" @click="router.push('/channelconfig/dataManagement/asyncTask')">
                                {{ '<查看详情' }}
                            </el-link>
                        </div>
                    </template>
                    <template #reference>
                        <el-button v-if="activeName == 'first'" v-auth="'CONFIRM_THROUGH'" type="primary" @click="sure">
                            确定转接
                        </el-button>
                    </template>
                </el-popover>
            </div>
            <el-button v-if="activeName == 'first' && !isHand" v-auth="'CONFIRM_THROUGH'" type="primary" @click="sure">
                确定转接
            </el-button>
        </div>

        <!-- 转接提示 -->
        <!-- <CommonDialog :appDialog="tips" ref="Dialogtips"> </CommonDialog> -->
        <!--选择客户弹框-->
        <Dialog ref="DialogRef" :app-dialog="appDialog">
            <DialogTable
                v-if="isShow"
                ref="dialogTableRef"
                :key="monthNum"
                @selectCustomer="selectCustomer"
                @cancleAllChange="cancleAllChange"></DialogTable>
        </Dialog>
        <!-- 转接提示 -->
        <Dialog ref="Dialogtips" :app-dialog="tips">
            <div class="content">{{ content }}</div>
        </Dialog>
        <!--选择接替的员工-->
        <ZWDepart ref="DepartRef" :is-local="true" @submit="getDeparts"></ZWDepart>
    </div>
</template>
<script lang="tsx" setup>
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import { reactive, ref, onMounted, computed, watch, nextTick } from 'vue';
import ZWPagination from '@/components/ZWPagination.vue';
import Search from './components/Search.vue';
import DialogTable from './components/DialogTable.vue';
import CommonDialog from '@/components/Dialog.vue';
import Dialog from './components/Dialog.vue';
import ZWDepart from '@/components/ZWDepart.vue';
import { useStore } from '@/store';
import { takeoverList, takeOver, handOverExport, isHandovering } from '@/api/employe/employeemanage/succession';
import { getSetionId, tableH, reSize } from '@/utils/utils';
import { ElMessage } from 'element-plus';
import { deepCopy } from '@/utils/helper';
import { ShowTaskMessage } from '@/hooks/TaskMessageHooks';
import { parabolaAnimation } from '@/utils/parabola';

import router from '@/router';
const monthNum = ref(0);
const store = useStore();
const ZWTableRef = ref(null);
const DialogRef = ref(null);
const DepartRef = ref(null);
const dialogTableRef = ref(null);
const activeName = ref('first');
const creators = ref([]);
const isShowCler = ref(false);
const content = ref('');
const crrentId = ref([]);
const isAll = ref(false);
const isShow = ref(true);

const selectText = ref('选择客户');

const takeoverParams = reactive({
    page_size: 15,
    page: 1,
    takeover_status: '',
    cust_name: ''
});
const dataParams = reactive({
    work_user_id: [],
    transfer_success_msg: '',
    cust_ids: [],
    select_type: 1
});
//refresh
const refresh = () => {
    monthNum.value += 1;
};
// 选中复选框
const table = computed(() => {
    return store.getters['table'];
});
//获取分配记录搜索结果
const onSearch = (data: any) => {
    takeoverParams.takeover_status = data.takeover_status;
    takeoverParams.cust_name = data.cust_name;
    reloadTable();
};

const cancelHandel = () => {
    appDialog.visible = false;
};
//客户弹框提交
const submitHandel = () => {
    isShow.value = false;
    dataParams.cust_ids = JSON.parse(JSON.stringify(crrentId.value));
    dataParams.cust_ids.length = crrentId.value.length;
    selectAllTotal.value = paramsTotal.value;
    isShow.value = true;
    cancelHandel();
    selectFocus();
    // reloadTable()
};
const appDialog = reactive({
    visible: false,
    title: '选择需转接的客户',
    width: '1000px',
    submit: submitHandel,
    cancel: cancelHandel,
    customerLength: 0,
    cancelText: '取消',
    submitText: '确定'
});
const formInline = reactive({
    trasferCustomer: [],
    trasferTo: []
});
const handleClick = (tab: string, event: Event) => {
    dataParams.work_user_id = [];
    dataParams.cust_ids = [];
    clearData();
};
//需要转接的客户
const handleTrasferCustomer = () => {
    appDialog.visible = true;
    // dialogTableRef.value ? dialogTableRef.value.search() : ''
};
//选接替的员工
const handleTrasferTo = () => {
    DepartRef.value.departVisble = true;
    DepartRef.value.selectedMember = creators.value;
};
const tableData = ref([]); //列表数据

const isHand = ref(false);
const handovering = ref(0);

const getIsHandovering = async () => {
    const res = await isHandovering({});
    if (res.handovering == 0) {
        isHand.value = false;
    } else {
        isHand.value = true;
        handovering.value = res.handovering;
    }
};

//获取状态
const getStatus = (val: string) => {
    const status = {
        '1': '接替完毕',
        '2': '等待接替',
        '3': '客户拒绝',
        '4': '接替成员客户达到上限',
        '5': '接替失败'
    };
    return status[val];
};

const selectAllTotal = ref(0);

const cancleAllArray = ref([]);

const cancleAllChange = (val: any) => {
    cancleAllArray.value = val;
    crrentId.value = val;
};

const paramsTotal = ref(0);

//获取需要转接的客户id
const selectCustomer = (val: any, total: any, isAllParam: any) => {
    isAll.value = isAllParam ? isAllParam : false;
    if (!isAllParam) {
        crrentId.value = val;
    }
    isAllParam ? (dataParams.select_type = 2) : (dataParams.select_type = 1);
    appDialog.customerLength = isAllParam ? total : val.length;
    paramsTotal.value = total;
};
//获取接替员工的id
const getDeparts = (res: any) => {
    creators.value = res;
    dataParams.work_user_id = getSetionId('id', creators.value);
    DepartRef.value.departVisble = false;
};
//确定转接
const sure = () => {
    if (isHand.value) return;
    if (dataParams.work_user_id.length == 0) {
        ElMessage.error('请选择接替的员工！');
        return;
    } else if (dataParams.cust_ids.length == 0 && !isAll.value) {
        ElMessage.error('请选择客户！');
        return;
    }
    tips.visible = true;
    const sureName = creators.value.map((v: any) => v.name);
    content.value =
        '您确定要将' +
        (isAll.value ? selectAllTotal.value : dataParams.cust_ids.length) +
        '名客户转交给员工' +
        sureName;
    tips.customerLength = isAll.value ? selectAllTotal.value : dataParams.cust_ids.length;
    reloadTable();
};
//导出列表
const exportData = e => {
    const params = {
        takeover_status: state.searchParams.takeover_status,
        cust_name: state.searchParams.cust_name
    };
    handOverExport(params).then((res: any) => {
        parabolaAnimation(e);
        ShowTaskMessage('批量导出异步任务创建成功');
    });
};
//删除员工
const changeDepart = (data: any) => {
    const removeDepart = creators.value.find((item: any) => !data.includes(item.id));
    const arr: any[] = creators.value.filter((item: any) => data.includes(item.id));
    dataParams.work_user_id = getSetionId('id', arr);
    creators.value = arr;
    DepartRef.value.removeItem(removeDepart);
};
//select Hover
const selectFocus = () => {
    if (appDialog.customerLength > 0) {
        isShowCler.value = true;
    }
};
//select Blur
const selectBlur = () => {
    if (appDialog.customerLength > 0) {
        isShowCler.value = false;
    }
};
//clear Tablelist
const clearData = () => {
    selectText.value = '选择客户';
    dataParams.cust_ids = [];
    appDialog.customerLength = 0;
    isShowCler.value = false;
    refresh();
    selectAllTotal.value = 0;
    cancleAllArray.value = [];
};
const tipsSubmit = e => {
    isShow.value = false;
    let params = dataParams;
    if (isAll.value) {
        params = {
            ...params,
            select_type: 2,
            ...dialogTableRef.value.state.searchParams
        };
        params.cust_ids = cancleAllArray.value;
    }
    // "select_type": 1, // 列表选择类型 1-表示选中的，后端默认设置为1，2-表示全选 ids为空时表示全部，不为空时表示要排除的
    //   "ids": [] // ids是原有的参数，不用调整，原来名称是什么就是什么
    takeOver(params)
        .then((res: any) => {
            isAll.value = false;
            crrentId.value = [];
            creators.value = [];
            dialogTableRef.value ? dialogTableRef.value.resetSearhForm() : '';
            dialogTableRef.value ? dialogTableRef.value.search() : '';
            tips.visible = false;
            clearData();
            activeName.value = 'second';
            reloadTable();
            parabolaAnimation(e);
            ShowTaskMessage('批量移交客户异步任务创建成功');
            isShow.value = true;
        })
        .catch(() => {
            tips.visible = false;
        });
};

const tips = reactive({
    visible: false,
    title: '转接提醒',
    width: '400px',
    submit: tipsSubmit,
    customerLength: 0,
    cancelText: '取消',
    submitText: '确定'
});

const defaultParams = {
    cust_name: '',
    takeover_status: ''
};
const tableRef = ref<HTMLElement | null>(null);
const state = reactive({
    searchParams: deepCopy(defaultParams)
});
const searchOption = computed(() => {
    return [
        {
            label: '客户名称',
            name: 'cust_name',
            value: '',
            type: 'input',
            placeholder: '请输入客户名称'
        },
        {
            label: '接替状态',
            name: 'takeover_status',
            value: [],
            type: 'select',
            placeholder: '请选择接替状态',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    setTimeout(() => {
                        resolve([
                            { id: '', name: '全部' },
                            { id: 1, name: '接替完毕' },
                            { id: 2, name: '等待接替' },
                            { id: 3, name: '客户拒绝' },
                            { id: 4, name: '接替成员客户达到上限' },
                            { id: 5, name: '接替失败' }
                        ]);
                    }, 300);
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        }
    ];
});

const search = (v: any) => {
    state.searchParams = {
        ...deepCopy(defaultParams),
        ...v,
        group_id: store.getters.group_id
    };
};
const reset = (v: any) => {
    state.searchParams = { ...deepCopy(defaultParams), group_id: store.getters.group_id };
};

// 表格
const tableOption = [
    {
        label: '客户名称',
        prop: 'cust',
        align: 'left',
        render({ row }) {
            return row.cust?.name || '--';
        }
    },
    {
        label: '原添加人',
        prop: 'handover_work',
        align: 'left',
        render({ row }) {
            return row.handover_work?.name || '--';
        }
    },
    {
        label: '接替员工',
        prop: 'takeover_work',
        align: 'left',
        render({ row }) {
            return row.takeover_work?.name || '--';
        }
    },
    {
        label: '接替状态',
        prop: 'takeover_status',
        align: 'left',
        render({ row }) {
            return getStatus(row.takeover_status);
        }
    },
    { label: '分配时间', prop: 'takeover_time', align: 'left' }
];
const fetchApi = () => {
    // 获取文件列表
    // return getFissionList
    return takeoverList;
};
// 刷新表格
const reloadTable = () => {
    tableRef.value.reload();
};

onMounted(() => {
    getIsHandovering();
});

watch(
    () => dataParams.cust_ids,
    val => {
        if (isAll.value) {
            selectText.value = '已选择' + selectAllTotal.value + '个客户';
        } else {
            selectText.value =
                dataParams.cust_ids.length > 0 ? '已选择' + dataParams.cust_ids.length + '个客户' : '选择客户';
        }
    },
    { immediate: true }
);
</script>
<style lang="scss" scoped>
.handle_button {
    margin-top: 16px;
}

.d-flex {
    display: flex;
}

.jc-end {
    justify-content: end;
}

.succession_container {
    height: calc(100vh - 142px);
    padding: 24px;
    padding-top: 10px;
    border: 1px solid #eaeaea;
    border-radius: 4px;
    box-sizing: border-box;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .succession_list {
        height: calc(100vh - 231px);
        display: flex;
        flex-direction: column;

        .zw-table {
            display: flex;
            flex-direction: column;
            flex: 1;
            overflow: hidden;

            :deep(.el-table) {
                flex: 1;

                .el-table__empty-block {
                    position: absolute;
                    top: 50%;
                    left: 50%;
                    transform: translate(-50%, -50%);
                }
            }
        }
    }
}

.content {
    min-height: 100px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.title-text {
    line-height: 50px;
    font-size: 14px;
    font-weight: 500;
    color: #33302d;

    .el-input__inner {
        height: 46px;
        background: #fffaf9;
        border-radius: 4px;
        border: 1px solid #ffeded;
    }
}

.export-btn {
    display: flex;
    justify-content: end;
    margin: 10px 0;
}

:deep(.placeholder) .el-input__inner::input-placeholder {
    color: #33302d;
}

.extend_select {
    width: 580px;

    // height: 46px;
    :deep .el-input__inner {
        background-color: #fffaf9;
        border-color: #fffaf0;

        &::input-placeholder {
            color: #33302d;
        }
    }
}
</style>
